package xrc.exception;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xrc.vo.RespBean;
import xrc.vo.RespBeanEnum;


/**
 * 全局异常处理类
 */
@RestControllerAdvice  // 返回ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RespBean ExceptionHandler(Exception e) {
        if (e instanceof GlobalException) {
            // 如果是全局异常
            // 将异常转为全局异常
            GlobalException ex = (GlobalException) e;
            return RespBean.error(ex.getRespBeanEnum());
        } else if (e instanceof BindException) {
            // 注意BindException导包为 org.springframework.validation.BindException
            // 如果是绑定异常
            // 将异常转为绑定异常
            BindException ex = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
            // 将后端异常信息捕获 并返回给前端
            respBean.setMessage("参数校验异常，" + ex.getBindingResult().getAllErrors()
                    .get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}
